import 'dart:io';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:gzmall_app/common/api.dart';
import 'package:gzmall_app/common/color_common.dart';
import 'package:gzmall_app/common/launch_util.dart';
import 'package:gzmall_app/common/net_util.dart';
import 'package:gzmall_app/common/refresh_listview.dart';
import 'package:gzmall_app/common/setting_util.dart';
import 'package:gzmall_app/common/share_util.dart';
import 'package:gzmall_app/common/toast_util.dart';
import 'package:gzmall_app/goods/goods_details_page.dart';
import 'package:gzmall_app/goods/goods_list_item_widget.dart';
import 'package:gzmall_app/model/brand.dart';
import 'package:gzmall_app/model/product.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class BrandsDetailsPage extends StatefulWidget {
  int id;

  BrandsDetailsPage({this.id});

  @override
  State<StatefulWidget> createState() => BrandsDetailsPageState(id: id);
}

class BrandsDetailsPageState extends State<BrandsDetailsPage>
    with TickerProviderStateMixin {
  int id;

  double _topPadding = 0.0;
  double _itemWidth;

  ScrollController _controller;
  TabController _tabController;
  Color _appBarBgColor;

  Brand _brand;
  List<Product> _products = [];

  RefreshListView _rTopListView, _rSpuListView1, _rSpuListView2;
  int _curPage = 1;

  BrandsDetailsPageState({this.id});

  @override
  void initState() {
    super.initState();
    init();
    _getBrands(id);
    _getBrandSpus(id, false, true, 1, _tabController.index);
  }

  @override
  Widget build(BuildContext context) {
    _topPadding = MediaQuery.of(context).padding.top;
    var size = MediaQuery.of(context).size;
    _itemWidth = (size.width - 12) / 2;
    double _tabBarViewPadding = 56.0 + 48.0 + _topPadding;
    return Scaffold(
      body: NestedScrollView(
        controller: _controller,
        headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
          return <Widget>[
            SliverOverlapAbsorber(
              handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context),
              child: SliverAppBar(
                pinned: true,
                expandedHeight: 350.0 + 48.0,
                automaticallyImplyLeading: false,
                forceElevated: false,
                bottom: PreferredSize(
                    preferredSize: Size(double.infinity, 48.0),
                    child: _createTabView()),
                flexibleSpace: _createBrandDetails(),
              ),
            ),
          ];
        },
        body: Container(
          margin: EdgeInsets.only(top: _tabBarViewPadding),
          child: _createTabBarView(),
        ),
      ),
    );
  }

  void init() {
    _controller = ScrollController();
    _controller.addListener(() {
      if (!mounted) return;
      setState(() {
        double scale = 0.0;
        if (_controller.offset > 0) {
          scale = _controller.offset / (56.0 + _topPadding);
        }
        if (scale > 1) scale = 1.0;
        int transparency = (255.0 * scale).toInt();
        _appBarBgColor = Color.fromARGB(transparency, 170, 170, 170);
      });
    });
    _tabController = TabController(length: 3, vsync: this);
    _tabController.addListener(() {
      switch (_tabController.index) {
        case 0:
          _getBrandSpus(id, false, true, 1, _tabController.index);
          break;
        case 1:
          _getBrandSpus(id, false, false, 1, _tabController.index);
          break;
        case 2:
          _getBrandSpus(id, true, false, 1, _tabController.index);
          break;
        default:
      }
    });
  }

  _createSearchAppBar() {
    return Container(
      height: 56.0 + _topPadding,
      padding: EdgeInsets.fromLTRB(10.0, _topPadding, 10.0, 0.0),
      color: _appBarBgColor,
      child: Row(
        children: <Widget>[
          GestureDetector(
            child: Icon(
              Icons.arrow_back_ios,
              color: Colors.white,
            ),
            onTap: () {
              Navigator.of(context).pop();
            },
          ),
          Expanded(
            child: GestureDetector(
              child: Container(
                height: 28.0,
                padding: const EdgeInsets.only(left: 15.0, right: 15.0),
                margin: const EdgeInsets.only(left: 10.0, right: 10.0),
                decoration: BoxDecoration(
                    color: ColorCommon.translucent1,
                    borderRadius: BorderRadius.circular(100.0)),
                child: Row(
                  children: <Widget>[
                    Padding(
                      padding: const EdgeInsets.only(right: 8.0),
                      child: Image.asset(
                        'images/search.png',
                        width: 16.0,
                        height: 16.0,
                      ),
                    ),
                    Text(
                      "搜索品牌内商品",
                      style: TextStyle(color: Colors.white),
                    ),
                  ],
                ),
              ),
              onTap: () {
                Navigator.of(context).pushNamed('/search_goods_page');
              },
            ),
          ),
          LaunchUtil.isInstallWeixin && !SettingUtil.isAppStoreAudit()
              ? GestureDetector(
                  child: Icon(
                    Icons.share,
                    color: Colors.white,
                  ),
                  onTap: () {
                    ShareUtil.showShareSelect(
                        context,
                        _brand.shareUrl,
                        _brand.shareTitle,
                        _brand.shareContent,
                        _brand.shareAvatar,
                        _brand.shareTitle);
                  },
                )
              : Container(),
        ],
      ),
    );
  }

  _createTabView() {
    return Container(
        color: ColorCommon.grey2,
        child: TabBar(
          controller: _tabController,
          labelColor: ColorCommon.primaryColor,
          unselectedLabelColor: ColorCommon.grey6,
          indicatorColor: Colors.transparent,
          tabs: <Widget>[
            Tab(text: "首页"),
            Tab(text: "商品"),
            Tab(text: "促销"),
          ],
        ));
  }

  _createBrandDetails() {
    return Container(
      color: Colors.white,
      child: Stack(
        children: <Widget>[
          Column(
            children: <Widget>[
              Expanded(
                child: _brand != null
                    ? CachedNetworkImage(
                        width: double.infinity,
                        imageUrl: _brand.avatar,
                        fit: BoxFit.cover,
                      )
                    : Container(),
              ),
              SizedBox(
                height: 200.0,
              ),
            ],
          ),
          Positioned(
            left: 0.0,
            right: 0.0,
            bottom: 0.0,
            child: Stack(
              children: <Widget>[
                Column(
                  children: <Widget>[
                    Container(
                      margin: const EdgeInsets.only(top: 20.0),
                      color: Colors.white,
                      child: Column(children: <Widget>[
                        Container(
                          margin: const EdgeInsets.only(
                              left: 15.0 + 86.0 + 15.0,
                              right: 15.0,
                              top: 15.0,
                              bottom: 20.0),
                          child: Row(
                            children: <Widget>[
                              Expanded(
                                child: Column(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    children: <Widget>[
                                      Text(_brand != null ? _brand.name : "",
                                          style: TextStyle(
                                              fontSize: 18.0,
                                              color: ColorCommon.black1)),
                                      // Padding(
                                      //   padding:
                                      //       const EdgeInsets.only(top: 5.0),
                                      //   child: Text(
                                      //       (_brand != null
                                      //               ? _brand.name
                                      //               : "") +
                                      //           " 27.3万粉丝",
                                      //       style: TextStyle(
                                      //           fontSize: 13.0,
                                      //           color: ColorCommon.grey3)),
                                      // ),
                                    ]),
                              ),
                              Container(
                                padding: const EdgeInsets.only(
                                    left: 10.0,
                                    right: 10.0,
                                    top: 4.0,
                                    bottom: 4.0),
                                decoration: BoxDecoration(
                                    border: Border.all(
                                        color: _brand != null &&
                                                _brand.favorited != null &&
                                                _brand.favorited
                                            ? ColorCommon.primaryColor
                                            : ColorCommon.grey1)),
                                child: InkWell(
                                  onTap: () {
                                    _favorites(_brand.id);
                                  },
                                  child: Text(
                                      _brand != null &&
                                              _brand.favorited != null &&
                                              _brand.favorited
                                          ? "已关注"
                                          : "+关注",
                                      style: TextStyle(
                                          fontSize: 13.0,
                                          color: _brand != null &&
                                                  _brand.favorited != null &&
                                                  _brand.favorited
                                              ? ColorCommon.primaryColor
                                              : ColorCommon.grey3)),
                                ),
                              ),
                            ],
                          ),
                        ),
                        Container(
                          padding: const EdgeInsets.only(
                              left: 10.0, right: 10.0, bottom: 20.0),
                          child: Text(_brand != null && _brand.intro != null
                              ? _brand.intro
                              : ""),
                        ),
                      ]),
                    ),
                    SizedBox(height: 48.0 + 10.0),
                  ],
                ),
                Container(
                  margin: const EdgeInsets.only(left: 15.0),
                  decoration: new BoxDecoration(
                    boxShadow: [
                      new BoxShadow(
                        color: ColorCommon.grey1,
                        blurRadius: 8.0,
                      )
                    ],
                  ),
                  child: _brand != null
                      ? CachedNetworkImage(
                          width: 86.0,
                          height: 86.0,
                          imageUrl: _brand.avatar,
                          fit: BoxFit.fill,
                        )
                      : Container(
                          width: 86.0,
                          height: 86.0,
                          color: ColorCommon.grey1,
                        ),
                ),
              ],
            ),
          ),
          _createSearchAppBar(),
        ],
      ),
    );
  }

  _createTabBarView() {
    return TabBarView(
      controller: _tabController,
      children: <Widget>[
        _createTopList(),
        _createProductList(1),
        _createProductList(2),
      ],
    );
  }

  _createTopList() {
    List<Widget> _hotProducts = [];
    if (_products != null && _products.length > 0) {
      _hotProducts = _products.map((p) {
        return _getTopProduct(p);
      }).toList();
    }
    _rTopListView = RefreshListView(
        enablePullUp: true,
        enablePullDown: true,
        onRefresh: _onRefresh,
        child: ListView(
          padding: const EdgeInsets.only(top: 0.0),
          children: <Widget>[
            Container(
              width: double.infinity,
              alignment: Alignment.center,
              margin: const EdgeInsets.only(top: 35.0),
              child: Text(
                "实时榜单",
                style: TextStyle(fontSize: 19.0, color: ColorCommon.black1),
              ),
            ),
            Container(
              width: double.infinity,
              alignment: Alignment.center,
              margin: const EdgeInsets.only(top: 10.0, bottom: 20.0),
              child: Text(
                "每日10点更新品牌热销榜",
                style: TextStyle(fontSize: 13.0, color: ColorCommon.grey8),
              ),
            ),
            Container(
              padding: const EdgeInsets.only(left: 10.0, right: 10.0),
              child: Wrap(
                runSpacing: 20.0,
                spacing: 8.0,
                children: _hotProducts,
              ),
            ),
          ],
        ));
    return Container(color: Colors.white, child: _rTopListView);
  }

  Widget _getTopProduct(Product product) {
    var _width = (MediaQuery.of(context).size.width - 10 - 10 - 10 - 10) / 3;
    return InkWell(
        onTap: () {
          Navigator.of(context).push(new MaterialPageRoute(builder: (_) {
            return new GoodsDetailsPage(productId: product.id);
          }));
        },
        child: Container(
          width: _width,
          child: Column(
            children: <Widget>[
              CachedNetworkImage(
                width: 80.0,
                height: 80.0,
                imageUrl: product.avatar,
                fit: BoxFit.fill,
              ),
              Padding(
                padding: const EdgeInsets.only(top: 5.0, bottom: 10.0),
                child: Text(
                  product.name,
                  style: TextStyle(fontSize: 15.0, color: ColorCommon.black1),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
              ),
              Text(
                "¥" + product.lowSalePrice.toString(),
                style: TextStyle(fontSize: 14.0, color: ColorCommon.black1),
              ),
            ],
          ),
        ));
  }

  _createProductList(int index) {
    return _buildGirdList(index);
  }

  Widget _buildGirdList(int index) {
    List<Widget> productWidgets = _products
        .map((item) => new InkWell(
              child: new GoodsListItemWidget(item, _itemWidth),
              onTap: () {
                Navigator.of(context).push(new MaterialPageRoute(builder: (_) {
                  return new GoodsDetailsPage(productId: item.id);
                }));
              },
            ))
        .toList();
    RefreshListView _rListView = RefreshListView(
      enablePullDown: true,
      enablePullUp: true,
      onRefresh: _onRefresh,
      child: GridView.count(
        shrinkWrap: true,
        padding: const EdgeInsets.only(left: 4.0, right: 4.0, top: 4.0),
        crossAxisSpacing: 4.0,
        mainAxisSpacing: 4.0,
        controller: new ScrollController(keepScrollOffset: false),
        crossAxisCount: 2,
        childAspectRatio: 0.65,
        children: productWidgets,
      ),
    );
    if (index == 1) {
      _rSpuListView1 = _rListView;
      return _rSpuListView1;
    } else if (index == 2) {
      _rSpuListView2 = _rListView;
      return _rSpuListView2;
    }
    return Container();
  }

  RefreshListView _getRListView(int index) {
    switch (index) {
      case 0:
        return _rTopListView;
      case 1:
        return _rSpuListView1;
      case 2:
        return _rSpuListView2;
      default:
        return null;
    }
  }

  void _onRefresh(bool up) {
    int p = up ? 1 : _curPage + 1;
    switch (_tabController.index) {
      case 0:
        _getBrandSpus(id, false, true, p, _tabController.index);
        break;
      case 1:
        _getBrandSpus(id, false, false, p, _tabController.index);
        break;
      case 2:
        _getBrandSpus(id, true, false, p, _tabController.index);
        break;
      default:
    }
  }

  _getBrands(int id) {
    if (id != null && id > 0) {
      NetUtil.get(
        context,
        Api.brands + "/" + id.toString(),
        (data, message) {
          if (!mounted) return;
          setState(() {
            _brand = Brand.fromJson(data);
          });
        },
      );
    }
  }

  _getBrandSpus(int id, bool promotion, bool hot, int page, int tcIndex) {
    if (id != null && id > 0) {
      bool isGetNew = page == 1;
      Map<String, String> params = {'page': page.toString()};
      if (promotion) {
        params['promotion'] = promotion.toString();
      }
      if (hot) {
        params['hot'] = hot.toString();
      }
      NetUtil.get(
          context,
          Api.brands + "/" + id.toString() + "/spus",
          (data, message) {
            if (!mounted) return;
            _curPage = page;
            var _dataList = (data as List)
                ?.map((e) => e == null ? null : Product.fromJson(e))
                ?.toList();
            setState(() {
              if (isGetNew) {
                _products = _dataList;
              } else {
                _products.addAll(_dataList);
              }
            });
            if (this._getRListView(tcIndex) != null) {
              this._getRListView(tcIndex).refreshCompleted(isGetNew,
                  hasMore:
                      _dataList != null && _dataList.length >= Api.pageSize);
            }
          },
          params: params,
          errorCallBack: (e) {
            if (this._getRListView(tcIndex) != null) {
              this._getRListView(tcIndex).refreshCompleted(isGetNew);
            }
          });
    }
  }

  _favorites(int id) {
    Map<String, String> params = {
      "type": "Brand",
      "id": id.toString(),
    };

    NetUtil.post(context, Api.favorites, (data, message) {
      ToastUtil.showMessageToast(message);
      if (_brand != null) {
        _getBrands(_brand.id);
      }
    }, params: params, isShowLoading: true);
  }
}
